package com.hengxinguotong.zhihuichengjian.ui.device;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.BlueToothDeviceListAdapter;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by liux on 2017/5/12.
 */

public class BlueToothListActivity extends BaseActivity {
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.scan_tv)
    HXTextView scanTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.device_lv)
    ListView deviceLv;
    @BindView(R.id.search_progress)
    ProgressBar searchProgress;
    private BlueToothDeviceListAdapter blueToothDeviceListAdapter;
    private List<BluetoothDevice> boundDevice;
    private BluetoothAdapter mBtAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        ButterKnife.bind(this);
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        boundDevice = new ArrayList<BluetoothDevice>();

        for (BluetoothDevice device : mBtAdapter.getBondedDevices()
                ) {
            boundDevice.add(device);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);

        blueToothDeviceListAdapter = new BlueToothDeviceListAdapter(boundDevice, this);
        deviceLv.setAdapter(blueToothDeviceListAdapter);
        deviceLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice bluetoothDevice;
                if (position > 0 && position <= boundDevice.size()) {
                    bluetoothDevice = boundDevice.get(position - 1);
                    Intent intent = new Intent();
                    intent.putExtra("bluetoothDevice", bluetoothDevice);
                    setResult(RESULT_OK, intent);
                    finish();
                } else if (position > boundDevice.size() + 1) {
                    mBtAdapter.cancelDiscovery();
                    BluetoothDevice _BluetoothDevice = blueToothDeviceListAdapter.getUnboundDevice().get(position - boundDevice.size() - 2);
                    Intent intent = new Intent();
                    intent.putExtra("bluetoothDevice", _BluetoothDevice);
                    // Set result and finish this Activity
                    setResult(Activity.RESULT_OK, intent);
                    finish();

                }

            }
        });

    }

    @OnClick({R.id.iv_back, R.id.scan_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.scan_tv:
                scanTv.setVisibility(View.GONE);
                searchProgress.setVisibility(View.VISIBLE);
                doDiscovery();
                break;
        }
    }


    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // If it's already paired, skip it, because it's been listed already
                if (device.getName() != null && device.getBondState() != BluetoothDevice.BOND_BONDED && blueToothDeviceListAdapter != null) {
                    blueToothDeviceListAdapter.addBluetoothDevice(device);
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                searchProgress.setVisibility(View.GONE);
                scanTv.setVisibility(View.VISIBLE);
                showToast("扫描完毕");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
    }


    /**
     * Start device discover with the BluetoothAdapter
     */
    private void doDiscovery() {
        if (mBtAdapter == null) {
            showToast("请打开蓝牙");
            finish();
            return;
        }

        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
        scanTv.setVisibility(View.GONE);
    }
}
